﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using X23.Application.RoleManagement;
using X23.Application.RoleManagement.Dto;
using X23.Application.UserManagement.Dto;
using X23.Extensions.AttributeExtensions;
using X23.Model.Const;
using X23.Model.Role;
using X23.Util.CacheUtil;
using X23.Util.LinqUtil;
using X23.Util.SerializationUtil;

namespace X23.Controllers
{
    /// <summary>
    /// 角色管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RoleController : BaseApiController
    {
        private readonly IRoleManagementService _roleManagementService;
        //private readonly ICacheService _cacheService;

        public RoleController(IRoleManagementService roleManagementService/*,ICacheService cacheService*/)
        {
            _roleManagementService = roleManagementService;
            //_cacheService = cacheService;
        }

        #region 权限
        /// <summary>
        /// 获取所有的角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<RoleDto>> GetAllRole()
        {
            return await _roleManagementService.GetListAsync(x=>true);
        }
        /// <summary>
        /// 获取菜单下的按钮权限
        /// </summary>
        /// <param name="url">菜单路径</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ButtonPermissionDto> GetButtonPermission(string url)
        {
            return await _roleManagementService.GetButtonPermissionWithCache(url, CurrentUser.Id);
        }
        #endregion

        #region 树形结构

        /// <summary>
        /// 获取角色树
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<RoleMenuTreeDto> GetRoleMenuTreeDto(int roleId)
        {
            return await _roleManagementService.GetRoleMenuTreeDto(roleId);
        }

        /// <summary>
        /// 添加修改角色树
        /// </summary>
        /// <param name="input">角色树</param>
        /// <returns></returns>
        [HttpPost]
        public async Task AddOrUpdateRoleMenuTreeDto(RoleMenuTreeDto input)
        {
            await VerifyAdministrator(input.Id);
            if (string.IsNullOrEmpty(input.Name))
            {
                throw new Exception("角色名称为空！");
            }
            await _roleManagementService.AddOrUpdateRoleMenuTreeDto(input);
        }
        #endregion

        #region 整体保存修改角色
        /// <summary>
        /// 整体保存修改角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> AllSaveAndUpdata(RoleCollectionDto input)
        {
            //var role = input.RoleDto;
            //var userRoleList = input.UserRoleDtos;
            //var menuButtonRoleList = input.MenuButtonRoleDtos;

            //if (role.Id != 0)
            //{
            //    role = await Add(role);
            //}
            //else
            //{
            //    role = await Update(role);
            //}
            //var roleId = role.Id;



            return await Task.FromResult(input != null);
        }
        #endregion

        #region 查询用户角色关系
        /// <summary>
        /// 获取用户下的角色
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<RoleDto>> GetRoleListByUserId(int userId)
        {
            return await _roleManagementService.GetRoleListByUserId(userId);
        }
        /// <summary>
        /// 获取角色下的用户
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<UserDto>> GetUserListByRoleId(int roleId)
        {
            return await _roleManagementService.GetUserListByRoleId(roleId);
        }
        #endregion

        #region CRUD
        /// <summary>
        /// 查询角色列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageData<RoleDto>> QueryData(Application.RoleManagement.Dto.QueryDto input)
        {
            Expression<Func<Role, bool>> predicate = x => string.IsNullOrEmpty(input.Name) || x.Name.Contains(input.Name);
            var result = await _roleManagementService.GetPageDataAsync(predicate, input.Pages, input.Rows);
            return result;
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<RoleDto> Add(RoleDto role)
        {
            return await _roleManagementService.AddAsync(role);
        }
        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<RoleDto> Update(RoleDto role)
        {
            await VerifyAdministrator(role.Id);
            return await _roleManagementService.UpdateAsync(role);
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<bool> Delete(int roleId)
        {
            await VerifyAdministrator(roleId);
            return await _roleManagementService.DeleteAsync(roleId);
        }

        /// <summary>
        /// 验证超级管理员
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        private async Task VerifyAdministrator(int roleId)
        {
            var role = await _roleManagementService.GetByIdAsync(roleId);
            if (role != null && (role.Name == "超级管理员" || role.Id == 1))
            {
                throw new Exception("超级管理员不可修改删除！");
            }
        }
        #endregion

    }
}
